import React, { useEffect, useState } from 'react'
import { NavBar, Form, Button, Input, CascadePicker, Space, Picker, TextArea, ImageUploader,Toast } from 'antd-mobile'
import { CloseCircleFill } from 'antd-mobile-icons'
import './index.scss'
import { useNavigate } from 'react-router-dom'
import { getHousesParamsAPI, addHousesAPI, getHousesCommunityAPI } from '../../apis/profile'
import { uploadImageAPI } from '../../apis/upload'
import { baseURL } from '../../utils/request'
import HousePackage from '../../components/housepackage'
import { getCityListAPI } from '../../apis/cityList'
import { getAreaAPI } from '../../apis/houselist'
import { getCurrentCity } from '../../utils'


export default function RentAdd() {
    const navigate = useNavigate()
    const [cityId, setCityId] = useState('')
    const [fileList, setFileList] = useState('')
    const [selectName, setSelectName] = useState('')
    const onFinish = (val) => {
        let submitData = {
            ...val,
            supporting: selectName,
            houseImg: fileList,
            community: val.community[0],
            floor: val.floor[0],
            oriented: val.oriented[0],
            roomType: val.roomType[0]
        }
        console.log(submitData);
        addHousesAPI(submitData).then(res => {
            if (res.status === 200) {
                Toast.show({
                    icon: 'success',
                    content: '添加成功',
                })
                navigate('/rent')
            }
        }).catch(error =>{
            Toast.show({
                icon: 'fail',
                content: '服务器偷懒了，请稍后再试~',
            })
            console.log(error);
        })

    }
    const [options, setOptions] = useState([])
    const [floorData, setFloorData] = useState([])
    const [orientedData, setOrientedData] = useState([])
    const [roomTypeData, setRoomTypeData] = useState([])
    const [supportingData, setSupportingData] = useState([])
    async function getHousesParams() {
        const res = await getHousesParamsAPI()
        const { floor, supporting, oriented, roomType } = res.body
        floorData[0] = floor
        supportingData[0] = supporting
        orientedData[0] = oriented
        roomTypeData[0] = roomType
    }
    useEffect(() => {
        getHousesParams()
        getAreaData()
    }, [])
    async function getAreaData() {
        const cityId = await getCurrentCity()
        setCityId(cityId.value)
        const res = await getHousesCommunityAPI(cityId.label, cityId.value)
        let data
        data = res.body.map(item => (
            {
                value: item.community,
                label: item.communityName
            }
        ))
        setOptions(data)
    }
    async function mockApi(key) {
        const children = await getAreaAPI(key)
        return children.body
    }
    function pickerSelect(key) {
        mockApi(key).then(data => {
            setOptions(options =>
                options.map(option => {
                    if (option.value === key) {
                        return {
                            ...option,
                            children: data.map(x => {
                                return {
                                    label: x.label,
                                    value: x.value,
                                }
                            }),
                        }
                    }
                    return option
                })
            )
        })
    }
    async function up(val) {
        let form = new FormData()
        form.append("file", val)
        const res = await uploadImageAPI(form)
        return { url: baseURL + res.body[0] }
    }
    function changeData(val) {
        let newval
        if (val.length > 0) {
            newval = (val.map(item => (item.url.substring(21)))).join("|")
        }
        setFileList(newval)
    }
    const handleSupporting = (selected) => {
        setSelectName(selected.join('|'))
    }
    return (
        <div className='rent__add'>
            <NavBar onBack={() => navigate(-1)} style={{ backgroundColor: '#eee' }}>发布房屋</NavBar>
            <div className='rent__add__content'>
                <Form
                    layout='horizontal'
                    name='form'
                    onFinish={(val) => onFinish(val)}
                    footer={
                        <Button block type='submit' color='primary' size='large'>
                            提交
                        </Button>
                    }
                >
                    <Form.Header>房源信息</Form.Header>
                    <Form.Item
                        name='community'
                        label='小区名称'
                        trigger='onConfirm'
                        onClick={(e, pw) => {
                            pw.current?.open()
                        }}
                    >
                        <CascadePicker
                            options={options}
                            onSelect={val => {
                                const key = val[0]
                                // if (!key) return
                                // pickerSelect(key)
                            }}
                        >{(items, { open }) => {
                            return (
                                <Space align='center' onClick={open}>

                                    {items.every(item => item === null)
                                        ? '未选择'
                                        : items.map(item => item?.label ?? '未选择').join(' - ')}
                                </Space>
                            )
                        }}</CascadePicker>
                    </Form.Item>

                    <Form.Item
                        name='price'
                        label='租金'
                        extra="￥/月"
                    >
                        <Input placeholder='请输入租金/月' />
                    </Form.Item>
                    <Form.Item
                        name='size'
                        label='建筑面积'
                        extra="㎡"
                    >
                        <Input placeholder='请输入建筑面积' />
                    </Form.Item>
                    <Form.Item
                        name='roomType'
                        label='户型'
                        trigger='onConfirm'
                        onClick={(e, pw) => {
                            pw.current?.open()
                        }}
                    >
                        <Picker
                            columns={roomTypeData}
                        >
                            {(items, { open }) => {
                                return (
                                    <Space align='center' onClick={open}>
                                        {(items[0] === undefined)
                                            ? '未选择'
                                            : items[0]?.label}
                                    </Space>
                                )
                            }}
                        </Picker>
                    </Form.Item>
                    <Form.Item
                        name='floor'
                        label='所在楼层'
                        trigger='onConfirm'
                        onClick={(e, pw) => {
                            pw.current?.open()
                        }}
                    >
                        <Picker
                            columns={floorData}
                        >
                            {(items, { open }) => {
                                return (
                                    <Space align='center' onClick={open}>
                                        {(items[0] === undefined)
                                            ? '未选择'
                                            : items[0]?.label}
                                    </Space>
                                )
                            }}
                        </Picker>
                    </Form.Item>
                    <Form.Item
                        name='oriented'
                        label='朝向'
                        trigger='onConfirm'
                        onClick={(e, pw) => {
                            pw.current?.open()
                        }}
                    >
                        <Picker
                            columns={orientedData}
                        >
                            {(items, { open }) => {
                                // console.log(items);
                                return (
                                    <Space align='center' onClick={open}>
                                        {(items[0] === undefined)
                                            ? '未选择'
                                            : items[0]?.label}
                                    </Space>
                                )
                            }}
                        </Picker>
                    </Form.Item>
                    <Form.Item
                        layout='vertical'
                        name='title'
                        label='房屋标题'
                    >
                        <TextArea
                            placeholder='请输入标题（如：整租 小区名 2室 5000元）'
                            maxLength={100}
                            rows={2}
                            showCount
                        />
                    </Form.Item>
                    <Form.Item
                        layout='vertical'
                        name='houseImg'
                        label='房屋图像'
                    >
                        <ImageUploader
                            value={fileList}
                            onChange={(val) => changeData(val)}
                            // beforeUpload = {(val,v)=>console.log(val,v)}
                            upload={(val) => up(val)}
                            multiple
                        />

                    </Form.Item>
                    <Form.Item
                        layout='vertical'
                        name='supporting'
                        label='房屋配置'
                    >
                        <HousePackage select onSelect={(val) => handleSupporting(val)} />
                    </Form.Item>
                    <Form.Item
                        layout='vertical'
                        name='description'
                        label='房屋描述'
                    >
                        <TextArea
                            placeholder='请输入房屋描述'
                            maxLength={100}
                            rows={2}
                            showCount
                        />
                    </Form.Item>
                </Form>
            </div>
        </div>
    )
}
